package com.jeesite.modules.storage.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.jeesite.common.config.Global;
import com.jeesite.modules.storage.common.MemberType;
import gui.ava.html.image.generator.HtmlImageGenerator;
import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class WebUtil {

    /*
     * 获取文件扩展名
     * @param filePath 文件路径
     * */
    public static String getExtension(String filePath){
        return filePath.substring(filePath.lastIndexOf("."));
    }

    /*
     * 获取文件名【含扩展名】
     * @param filePath 文件路径
     * */
    public static String getFileName(String filePath){
        filePath = filePath.replace("\\","/");
        String[] array = filePath.split("/");
        return array[array.length - 1];
    }

    /*
     * 获取文件名【不含扩展名】
     * @param filePath 文件路径
     * */
    public static String GetFileNameWithoutExtension(String filePath){
        String fileName = getFileName(filePath);
        return fileName.substring(0,fileName.lastIndexOf(".") );
    }

    /*
     * 检查文件，如果文件夹不存在，则创建
     * */
    public static void checkFile(String filePath){
        String fileName = getFileName(filePath);
        filePath = filePath.replace(fileName,"");
        File file =new File(filePath);
        if  (!file.exists()  && !file.isDirectory())
        {
            file.mkdirs();
        }
    }

    /*
     * 获取静态资源目录
     */
    public static String getResourcePath(String path){
        return Global.getConfig("storage.path.web.resource") + path;
    }

    /*
     * 获取用户文件路径
     * */
    public static String getRootPath(String path){
        return Global.getConfig("storage.path.web.root") + path;
    }

    /*
     * 获取跟路径
     * */
    public static String getUserFilesPath(String path){
        return Global.getConfig("storage.path.web.userfiles") + path;
    }

    /*
     * 获取Html路径
     * @param fileName 文件名
     * @return html完整路径
     */
    public static String getHtmlPath(String fileName){
        return getResourcePath("/html/" + fileName);
    }

    /*
     * 读取文件内容
     * @param fileName 文件路径
     * @return 文件内容
     */
    public static String readFileToString(String fileName) {
        String encoding = "UTF-8";
        File file = new File(fileName);
        Long length = file.length();
        byte[] bytes = new byte[length.intValue()];
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            fileInputStream.read(bytes);
            fileInputStream.close();
            return new String(bytes, encoding);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /*
     * 生成二维码
     * @param content 内容
     * @param width 宽度
     * @param height 高度
     * @param filePath 路径
     * @return 信息
     * */
    public static void buildQRCode(Integer width,Integer height, String content,String filePath) {
        try {
            checkFile(filePath);
            int BLACK = 0x000000;
            int WHITE = 0xFFFFFF;
            String FORMAT_NAME = "png";

            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, "0");

            MultiFormatWriter writer = new MultiFormatWriter();
            BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

            BufferedImage image = new BufferedImage(bitMatrix.getWidth(), bitMatrix.getHeight(), BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < bitMatrix.getWidth(); x++) {
                for (int y = 0; y < bitMatrix.getHeight(); y++) {
                    image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
                }
            }

            File imgFile = new File(filePath);
            ImageIO.write(image, FORMAT_NAME, imgFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * 获取H5网址
     * @param url 网址
     * */
    public static String getH5FullUrl(String url){
        return (Global.getConfig("storage.url.h5") + url);
    }

    /*
     * 获取Web网址
     * @param url 网址
     * */
    public static String getWebUrl(String url){
        return Global.getConfig("storage.url.web") + url;
    }

    /*
     * 获取Web UserFiles网址
     * @param url 网址
     * */
    public static String getWebUserFilesUrl(String url){
        return getWebUrl("/userfiles" + url);
    }

    /*
     * 获取Web static网址
     * @param url 网址
     * */
    public static String getWebResourceUrl(String url){
        return getWebUrl("/static" + url);
    }

    /*
     * Html转图片
     * @param templateName 模板名称
     * @param filePath 文件路径
     * */
    public static void html2Image(String filePath, Map<String,String> map, String imgPath) {
        try{
            checkFile(imgPath);
            HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
            String html = readFileToString(filePath);
            if(map != null){
                for(Map.Entry<String, String> entry : map.entrySet()){
                    html = html.replace(entry.getKey(),entry.getValue());
                }
            }
            imageGenerator.loadHtml(html);
            imageGenerator.getBufferedImage();
            imageGenerator.saveAsImage(imgPath);
        }catch (Exception e){}
    }

//    /*
//     * 压缩图片
//     * @param sourcePath 源文件
//     * @param destPath 目标文件
//     * @param width 宽度
//     * @param height 高度
//     * */
//    public static void thumbnails(String sourcePath, String destPath, Integer width,Integer height) {
//        try {
//            checkFile(destPath);
//            Thumbnails.of(sourcePath).size(width, height).keepAspectRatio(false).toFile(destPath);
//        } catch (Exception e1) {
//        }
//    }

    /*
     * 压缩图片
     * @param sourcePath 源文件
     * @param destPath 目标文件
     * */
    public static void thumbnails1(String sourcePath, String destPath) {
        try {
            checkFile(destPath);
            Thumbnails.of(sourcePath).scale(0.8f).toFile(destPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getTradeNoByOrderId(String  orderId){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMddhhmmss");
        return orderId + simpleDateFormat.format(new Date());
    }

    public static String getOrderIdByTradeNo(String  payTradeNo){
        return payTradeNo.substring(0,payTradeNo.length() - 10);
    }

    /*
    * 获取销售价格
    * @param type 会员类型
    * @param map 不同价格字典
    * */
    public static Double getSalePrice(String type,Map priceMap){
        double vipPrice = !priceMap.containsKey("agentPrice") ? 0d : Double.parseDouble(String.valueOf(priceMap.get("vipPrice")));
        double memberPrice = !priceMap.containsKey("agentPrice") ? 0d : Double.parseDouble(String.valueOf(priceMap.get("memberPrice")));
        double agentPrice = !priceMap.containsKey("agentPrice") ? 0d : Double.parseDouble(String.valueOf(priceMap.get("agentPrice")));

        Double result = 0d;
        if(type.equals(MemberType.VIP_TYPE)){
            result = vipPrice;
        }else if(type.equals(MemberType.DIRECT_CUSTOMER_TYPE)){
            result = memberPrice;
        }


        return result;
    }

    /*
     * 获取代理价格
     * @param type 会员类型
     * @param map 不同价格字典
     * */
    public static Double getAgentPrice(Map priceMap){
        double agentPrice = Double.parseDouble(String.valueOf(priceMap.get("agentPrice")));

        Double result = 0d;

        result = agentPrice;

        return result;
    }
}
